<template>
  <div id="Application">
    <!-- 游戏区域 -->
    <div class="container">
      <!-- 底部挡板 -->
      <div class="board" :style="{ left: boardX + 'px' }"></div>
      <!-- 弹球 -->
      <div class="ball" :style="{ left: ballX + 'px', top: ballY + 'px' }"></div>
      <!-- 游戏结束提示 -->
      <h1 v-if="fail" style="text-align: center">游戏失败</h1>
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'

export default {
  name: 'GameBoard', // 修改组件名称
  setup() {
    const boardX = ref(0)
    const ballX = ref(0)
    const ballY = ref(0)
    const rateX = ref(0.1)
    const rateY = ref(0.1)
    const fail = ref(false)

    const keydown = (event) => {
      if (event.key === 'ArrowLeft') {
        if (boardX.value > 10) {
          boardX.value -= 20
        }
      } else if (event.key === 'ArrowRight') {
        if (boardX.value < 440 - 80) {
          boardX.value += 20
        }
      }
    }

    const enterKeyup = () => {
      document.addEventListener('keydown', keydown)
    }

    onMounted(() => {
      enterKeyup()
      rateX.value = Math.random() * 0.5 + 0.1
      rateY.value = Math.random() * 0.5 + 0.1
      const timer = setInterval(() => {
        if (ballX.value + rateX.value >= 440 - 30) {
          rateX.value *= -1
        }
        if (ballX.value + rateX.value <= 0) {
          rateX.value *= -1
        }
        if (ballY.value + rateY.value <= 0) {
          rateY.value *= -1
        }
        ballX.value += rateX.value
        ballY.value += rateY.value
        if (ballY.value >= 440 - 30 - 10) {
          if (boardX.value <= ballX.value + 30 && boardX.value + 80 >= ballX.value) {
            rateY.value *= -1
          } else {
            clearInterval(timer)
            fail.value = true
          }
        }
      }, 2)
    })

    return {
      boardX,
      ballX,
      ballY,
      fail,
    }
  },
}
</script>

<style>
body {
  margin: 0;
  padding: 0;
}
.container {
  position: relative;
  margin: 0 auto;
  width: 440px;
  height: 440px;
  background-color: blanchedalmond;
}
.ball {
  position: absolute;
  width: 30px;
  height: 30px;
  left: 0px;
  top: 0px;
  background-color: orange;
  border-radius: 30px;
}
.board {
  position: absolute;
  left: 0;
  bottom: 0;
  height: 10px;
  width: 80px;
  border-radius: 5px;
  background-color: red;
}
</style>

